package com.mengniu.commerce.admin.controller.auth;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import cn.hutool.core.util.ObjectUtil;
import com.mengniu.commerce.admin.api.RemoteSocialService;
import com.mengniu.commerce.admin.api.domain.SysUser;
import com.mengniu.commerce.admin.form.SocialLoginBody;
import com.mengniu.commerce.admin.form.SocialLogoutBody;
import com.mengniu.commerce.admin.service.auth.SysLoginService;
import com.mengniu.commerce.admin.service.system.ISysUserService;
import com.mengniu.common.social.config.properties.SocialLoginConfigProperties;
import com.mengniu.common.social.config.properties.SocialProperties;
import com.mengniu.common.social.config.utils.SocialUtils;
import com.mengniu.common.social.mengniu98k.AuthMengniuUser;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.web.bind.annotation.*;
import com.mengniu.commerce.admin.form.LoginBody;
import com.mengniu.commerce.admin.form.RegisterBody;
import com.mengniu.commerce.common.core.domain.R;
import com.mengniu.commerce.common.core.utils.JwtUtils;
import com.mengniu.commerce.common.core.utils.StringUtils;
import com.mengniu.commerce.common.security.auth.AuthUtil;
import com.mengniu.commerce.common.security.service.TokenService;
import com.mengniu.commerce.common.security.utils.SecurityUtils;
import com.mengniu.commerce.admin.api.model.LoginUser;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * token 控制
 *
 * @author yz_sm
 */
@RestController
public class TokenController {
    @Resource
    private TokenService tokenService;

    @Resource
    private SysLoginService sysLoginService;

    @Resource
    private SocialProperties socialProperties;

    @Resource
    private RemoteSocialService remoteSocialService;

    @Resource
    private ISysUserService userService;

    @PostMapping("/login")
    public R<?> login(@RequestBody LoginBody form) {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    @DeleteMapping("/logout")
    public R<?> logout(HttpServletRequest request) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @PostMapping("/refresh")
    public R<?> refresh(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    @PostMapping("/register")
    public R<?> register(@RequestBody RegisterBody registerBody) {
        // 用户注册
        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
        return R.ok();
    }

    /**
     * 第三方登录请求
     *
     * @param source 登录来源
     * @return 结果
     */
    @GetMapping(value = {"/", "/binding"})
    public R<String> authBinding(String source) {
        if (!socialProperties.getEnabled()) {
            return R.fail("三方账号登录功能未开启！");
        }
        SocialLoginConfigProperties obj = socialProperties.getType().get(source);
        if (ObjectUtil.isNull(obj)) {
            return R.fail(source + "平台账号暂不支持");
        }
        AuthRequest authRequest = SocialUtils.getAuthRequest(source, socialProperties);
        String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
        return R.ok(authorizeUrl, "操作成功");
    }

    /**
     * 第三方登录回调业务处理 绑定授权
     *
     * @param loginBody 请求体
     * @return 结果
     */
    @PostMapping("/social/callback")
    public R<Map<String, Object>> socialCallback(@RequestBody @Valid SocialLoginBody loginBody) {
        // 获取第三方登录信息
        AuthResponse<AuthMengniuUser> response = SocialUtils.loginAuth(
                loginBody.getSource(), loginBody.getCode(),
                loginBody.getState(), socialProperties);
        AuthMengniuUser authUserData = response.getData();
        // 判断授权响应是否成功
        if (!response.ok()) {
            return R.fail(response.getMsg());
        }
        //社交账号注册
        SysUser sysUser = sysLoginService.socialRegister(authUserData);
        //授予角色
        List<Long> roleIds = Arrays.asList(3L);
        userService.insertUserAuth(sysUser.getUserId(), (Long[]) roleIds.toArray());
        // 用户登录
        LoginUser userInfo = sysLoginService.loginByQrCode(sysUser.getUserName());
        // 获取登录token
        Map<String, Object> token = tokenService.createToken(userInfo);
        token.put("authUserData", authUserData);
        return R.ok(token);
    }


    /**
     * 取消授权
     *
     * @param socialId socialId
     */
    @DeleteMapping(value = "/unlock")
    public R<Boolean> unlockSocial(String socialId) {
        R<Boolean> booleanR = remoteSocialService.unlock(socialId);
        Boolean rows = booleanR.getData();
        return rows ? R.ok() : R.fail("取消授权失败");
    }


    @DeleteMapping("/social/logout")
    public R<?> socialLogout(HttpServletRequest request, @RequestBody @Valid SocialLogoutBody socialLogoutBody) {
        //先退出蒙牛
        Boolean logout = SocialUtils.logout(
                socialLogoutBody.getSource(), socialLogoutBody.getState(), socialProperties);
        // 判断授权响应是否成功
        if (!logout) {
            return R.fail("登出蒙牛账号失败");
        }
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }
}
